import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

public class Main {
    private static final String COM_FORMAT="php artisan make:migration add_%s_to_%s_table --table=%s";

    public static void main(String[] args) throws Exception {
        String rootPath=getRootPath();
        String fileName=rootPath+"\\data.json";
        List<JSONObject> json=JSON.parseArray(readFile(fileName),JSONObject.class);

        List<String> coms=new ArrayList<>();
        for(JSONObject row : json){
            String table=row.getString("table");
            JSONArray columns=row.getJSONArray("columns");

            String keys=StringUtils.join(columns,"_");
            String com=String.format(COM_FORMAT,keys,table,table);
            coms.add(com);
        }

        String content=StringUtils.join(coms,"\n");
        String path=rootPath+"\\command.txt";
        Boolean success=writeFile(content,path);
        if(success){
            System.out.println("批量生成成功");
        }else{
            System.out.println("批量生成失败");
        }
    }

    private static String readFile(String fileName) {
        String json = "";
        try {
            FileReader fileReader = new FileReader(fileName);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line = "";
            do {
                line = bufferedReader.readLine();
                if (line != null) {
                    json += line;
                } else {
                    break;
                }
            } while (true);

            fileReader.close();
            bufferedReader.close();
        } catch (Exception e) {
            System.out.println("读取文件错误");
        }
        return json;
    }

    private static Boolean writeFile(String content,String path){
        try{
            FileWriter fileWriter = new FileWriter(path);
            fileWriter.write(content);
            fileWriter.close();
            return true;
        }catch (Exception e){
            System.out.println("写入文件错误");
            return false;
        }
    }

    private static String getRootPath() throws Exception{
        return (new File("")).getCanonicalPath() ;
    }
}
